package com.tang.wc;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * DateStreamApi
 *
 * @author tang
 * @since 2023/5/29 11:55
 */
public class WordCountStreamDemo {

    public static void main(String[] args) throws Exception {
        // 1. 获取环境
        StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();
        // 2. 获取数据源
        DataStreamSource<String> stringDataStreamSource = environment.readTextFile("input/word.txt");
        // 3. 处理数据，切分，转换
        SingleOutputStreamOperator<Tuple2<String, Integer>> tuple2SingleOutputStreamOperator = stringDataStreamSource.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {

            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                // 按照 空格 切分
                String[] words = value.split(" ");
                for (String word : words) {
                    // 转换成 二元组 （word，1）
                    Tuple2<String, Integer> wordsAndOne = Tuple2.of(word, 1);
                    // 通过 采集器 向下游发送数据
                    out.collect(wordsAndOne);
                }
            }

        });


        // 4 分组
        KeyedStream<Tuple2<String, Integer>, Object> wordAndOneKs = tuple2SingleOutputStreamOperator.keyBy(
                new KeySelector<Tuple2<String, Integer>, Object>() {
                    @Override
                    public Object getKey(Tuple2<String, Integer> value) throws Exception {
                        return value.f0;
                    }
                });

        // 5 聚合
        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = wordAndOneKs.sum(1);

        // 6 输出
        sum.print();

        // 7 执行DataStream
        environment.execute();

    }

}
